package cn.webwheel.whtml;

import com.sun.net.httpserver.HttpServer;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.text.ParseException;
import java.util.prefs.Preferences;

public class MainFrame extends JFrame {

    static Preferences preferences = Preferences.userNodeForPackage(MainFrame.class);

    static BufferedImage icon, icon2;
    static {
        try {
            icon = ImageIO.read(MainFrame.class.getResource("/res/icon.png"));
            icon2 = ImageIO.read(MainFrame.class.getResource("/res/icon2.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final MainFrameIconifiedListener iconifiedListener;

    private JPanel contentPane;
    private JButton btRun;
    private JSpinner spPort;
    private JTextField tfRoot;
    private JButton btSelect;
    private JLabel label;

    private ImageIcon iconRun = new ImageIcon(getClass().getResource("/res/run.png"));
    private ImageIcon iconRun2 = new ImageIcon(getClass().getResource("/res/run2.png"));
    private ImageIcon iconStop = new ImageIcon(getClass().getResource("/res/stop.png"));
    private ImageIcon iconStop2 = new ImageIcon(getClass().getResource("/res/stop2.png"));

    private HttpServer server;

    public MainFrame() {
        super("WebWheel原型设计");

        setIconImage(icon);

        setupSpPort();

        tfRoot.setText(preferences.get("root", ""));

        btRun.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                switchRunStatus();
            }
        });

        btSelect.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                selectRoot();
            }
        });

        addWindowListener(iconifiedListener = new MainFrameIconifiedListener(this));

        label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(URI.create("http://code.google.com/p/webwheel/"));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            String decorate = "<html><u color=#005580>";

            @Override
            public void mouseEntered(MouseEvent e) {
                String s = label.getText();
                if (!s.startsWith("<")) {
                    label.setText(decorate + s);
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                String s = label.getText();
                if (s.startsWith("<")) {
                    label.setText(s.substring(decorate.length()));
                }
            }
        });

        setContentPane(contentPane);

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
        setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void selectRoot() {
        JFileChooser fileChooser = new JFileChooser(tfRoot.getText());
        fileChooser.setDialogTitle("请选择网站根目录");
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.addChoosableFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "网站根目录";
            }
        });
        int op = fileChooser.showOpenDialog(MainFrame.this);
        if (op == JFileChooser.APPROVE_OPTION) {
            tfRoot.setText(fileChooser.getSelectedFile().getAbsolutePath());
        }
    }

    private void switchRunStatus() {
        if (server == null) {
            File dir = new File(tfRoot.getText());
            if (!dir.exists() || !dir.isDirectory()) {
                JOptionPane.showMessageDialog(MainFrame.this, "请选择正确的网站根目录", "警告", JOptionPane.WARNING_MESSAGE);
                return;
            }
            int port = ((Number) spPort.getValue()).intValue();
            try {
                server = HttpServer.create(new InetSocketAddress(port), 0);
                server.createContext("/", new WHandler(dir, "utf-8"));
                server.start();
            } catch (Exception ex) {
                server = null;
                ex.printStackTrace();
                JOptionPane.showMessageDialog(MainFrame.this, "无法启动服务。" + ex.toString(), "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            preferences.put("port", String.valueOf(port));
            preferences.put("root", tfRoot.getText());
            btRun.setIcon(iconStop);
            btRun.setRolloverIcon(iconStop2);
            btRun.setToolTipText("停止服务");
            setIconImage(icon2);
            iconifiedListener.setRunning(true);
            try {
                Desktop.getDesktop().browse(URI.create("http://localhost" + (port == 80 ? "" : ":" + port)));
                setState(ICONIFIED);
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(MainFrame.this, "无法打开浏览器。" + e.toString(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            server.stop(0);
            server = null;
            btRun.setIcon(iconRun);
            btRun.setRolloverIcon(iconRun2);
            btRun.setToolTipText("启动服务");
            setIconImage(icon);
            iconifiedListener.setRunning(false);
        }
        spPort.setEnabled(server == null);
        tfRoot.setEnabled(server == null);
        btSelect.setEnabled(server == null);
    }

    private void setupSpPort() {
        spPort.setModel(new SpinnerNumberModel(preferences.getInt("port", 80), 1, 65535, 1));
        ((JSpinner.NumberEditor)spPort.getEditor()).getTextField().setFormatterFactory(new JFormattedTextField.AbstractFormatterFactory() {
            @Override
            public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
                return new JFormattedTextField.AbstractFormatter() {
                    @Override
                    public Object stringToValue(String text) throws ParseException {
                        try {
                            return Integer.parseInt(text);
                        } catch (NumberFormatException e) {
                            throw new ParseException(null, 0);
                        }
                    }

                    @Override
                    public String valueToString(Object value) throws ParseException {
                        return String.valueOf(value);
                    }
                };
            }
        });
    }

    public static void main(String[] args) {
        System.setProperty("sun.java2d.noddraw", "true");
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(new NimbusLookAndFeel());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                new MainFrame();
            }
        });
    }
}
